//
//  RYCListModelIdentifierPagingPolicy.m
//  EWallet
//
//  Created by hemingway payegis on 13-3-4.
//  Copyright (c) 2013年 payegis. All rights reserved.
//

#import "RYCListModelIdentifierPagingPolicy.h"

#define RYCIdentifierDefault @""

@interface RYCListModelIdentifierPagingPolicy ()
@property (nonatomic, retain) NSString* requestIdentifier;
@property (nonatomic, readwrite, retain) NSString* currentPageIdentifier;
@end


@implementation RYCListModelIdentifierPagingPolicy

- (void)dealloc
{
    self.requestIdentifier = nil;
    self.identifierKeyName = nil;
    self.otherParams = nil;
    self.currentPageIdentifier = nil;
    [super dealloc];
}

- (id)init
{
    self = [super init];
    if (self)
    {
        _pageSize = 20;
    }
    return self;
}

- (NSDictionary*)pagingParamsForSendRequest:(RYCHTTPListModel*)listModel
{
    self.requestIdentifier = RYCIdentifierDefault;
    
    NSMutableDictionary* dict = [NSMutableDictionary dictionary];
    
    if (RYCHTTPRequestModelOperation_Normal == listModel.operation
        || RYCHTTPRequestModelOperation_Refresh == listModel.operation)
    {
        //NOOP
    }
    else if (RYCHTTPRequestModelOperation_Forward ==  listModel.operation)
    {
        NSArray* array = listModel.lastResponseList;
        if ([array count] > 0)
        {
            id obj = [array lastObject];
            NSString* identifier = [obj identifierForInstance:obj];
            self.requestIdentifier = identifier;
        }
    }
    else if (RYCHTTPRequestModelOperation_Backward == listModel.operation)
    {
        NSArray* array = listModel.lastResponseList;
        if ([array count] > 0)
        {
            id obj = [array objectAtIndex:0];
            NSString* identifier = [obj identifierForInstance:obj];
            self.requestIdentifier = identifier;
        }
    }

    if (_requestIdentifier!=nil && ![_requestIdentifier isEqualToString:@""]) {
        [dict setObject:_requestIdentifier forKey:self.identifierKeyName];
    }
    
//    [dict setObject:_requestIdentifier forKey:self.identifierKeyName];
    [dict setObject:[NSNumber numberWithInteger:_pageSize] forKey:@"pageSize"];
    if (_otherParams)
    {
        [dict addEntriesFromDictionary:_otherParams];
    }
    return dict;
}

- (void)didModelFinished:(RYCHTTPListModel*)listModel
{
    self.currentPageIdentifier = self.requestIdentifier;
}

- (void)reset:(RYCHTTPListModel*)listMode
{
    self.currentPageIdentifier = nil;
    self.requestIdentifier = nil;
}

- (BOOL)hasNextPage:(RYCHTTPListModel*)listMode
{
    if ([listMode.lastResponseList count] < _pageSize)
    {
        return NO;
    }
    return YES;
}

@end
